package com.unicom.room.realm;

import com.unicom.room.mapper.UserMapper;
import com.unicom.room.model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {

	@Autowired
	private UserMapper userMapper;

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String name=(String) SecurityUtils.getSubject().getPrincipal();
		SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
		User user = userMapper.selectByUsername(name);
		info.addRole(String.valueOf(user.getUserType()));
		return info;
	}

	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("token.getPrincipal:" + token.getPrincipal());
		System.out.println("token.getCredentials:" + token.getCredentials());
		String name = token.getPrincipal().toString();
		User user = userMapper.selectByUsername(name);
		if (user != null) {
			// Object principal, Object credentials, String realmName
			AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getName(), user.getPassword(), getName());
			return authcInfo;
		} else {
			return null;
		}
	}

}
